package service

import (
	"errors"
	"fmt"
	"gin-luban-server/global"
	"gin-luban-server/model"
	"gin-luban-server/model/request"
	"github.com/360EntSecGroup-Skylar/excelize/v2"
	"gorm.io/gorm"
)
//@author: heyibo
//@function: CreateDatabase
//@description: 创建一个数据库信息
//@param: database CMDBDatabase
//@return: err error, database model.CMDBDatabase

func CreateDatabase(database model.CMDBDatabase) (err error) {
	if !errors.Is(global.GVA_DB.Where("cluster_name =  ?", database.ClusterName).First(&model.CMDBDatabase{}).Error, gorm.ErrRecordNotFound) {
		return errors.New("存在相同集群名称！")
	}
	return global.GVA_DB.Create(&database).Error
}

//@author: heyibo
//@function: DeleteDatabase
//@description: 删除数据库信息
//@param: id ,database CMDBDatabase
//@return: err error

func DeleteDatabase(id float64) (err error) {
	var database model.CMDBDatabase
	db := global.GVA_DB.Where("id = ?", id).Preload("DatabaseUser").First(&database)
	if len(database.DatabaseUser) > 0 {
		return errors.New("有账户正在使用禁止删除")
	}
	err = db.Delete(&database).Error
	return err
}

//@author: heyibo
//@function: UpdateDatabase
//@description: 更改一个角色
//@param: database model.CMDBDatabase
//@return:err error, database model.CMDBDatabase
func UpdateDatabase(database model.CMDBDatabase) (err error) {
	var total int64
	var bases []model.CMDBDatabase
	err = global.GVA_DB.Where("cluster_name = ? AND id != ?",database.ClusterName,database.ID).Find(&bases).Count(&total).Error
	if total >= 1 {
		return errors.New("存在相同集群名称!")
	}
	// 通过唯一ID进行更新
	err = global.GVA_DB.Where("id = ?", database.ID).First(&model.CMDBDatabase{}).Updates(&database).Error
	return err
}

//@author: heyibo
//@function: FindDatabasetById
//@description: 根据Id查询数据
//@param: id int
//@return: err error, database model.CMDBDatabase
func FindDatabaseById(id float64) (err error, database model.CMDBDatabase) {
	err = global.GVA_DB.Where("id = ?", id).First(&database).Error
	return err, database
}

//@author: heyibo
//@function: GetAuthorityInfoList
//@description: 分页获取数据
//@param: info request.PageInfo
//@return: err error, list interface{}, total int64
func GetDatabaseInfoList(info request.SearchDatabaseParams) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.GVA_DB.Model(&model.CMDBDatabase{})
	var databaseList []model.CMDBDatabase
	if info.DatabaseType !="" {
		db = db.Where("database_type = ?",info.DatabaseType)
	}
	if info.VIP != "" {
		db = db.Where("vip LIKE ?","%"+info.VIP+"%")
	}
    if info.ClusterName != "" {
		db = db.Where("cluster_name = ?",info.ClusterName)
	}
	err = db.Count(&total).Error

	if err != nil {
		return err, databaseList, total
	} else {
		db = db.Limit(limit).Offset(offset)
		err = db.Preload("DatabaseUser").Preload("Project").Find(&databaseList).Error
	}
	return err, databaseList, total
}

//@author: heyibo
//@function: ParseDatabaseInfoList2Excel
//@description: 导出数据
//@param: atabase model.CMDBDatabase, filePath string
//@return: err error
func ParseDatabaseInfoList2Excel(database model.CMDBDatabaseUser, filePath string) error {
	db := global.GVA_DB.Model(&model.CMDBDatabaseUser{})
	var databaseList []model.CMDBDatabaseUser
	if database.ClusterName != "" {
		db = db.Where("cluster_name = ?", database.ClusterName)
	}
	err := db.Preload("Database").Preload("Database.Project").Preload("Database.SysCompanyInfo").Preload("Project").Find(&databaseList).Error
	if err != nil {
		return err
	}
	// 写入 excel文件
	excel := excelize.NewFile()
	excel.SetSheetRow("Sheet1","A1",&[]string{"ID","集群名称", "数据库类型", "VIP地址", "端口", "环境名称",
		"IDC位置", "域名地址", "部署路径", "IP地址", "数据库大小", "集群所属项目", "公司名称","数据库名称","数据库所属项目","用户名称","权限"})
	for i, Form := range databaseList {
		axis := fmt.Sprintf("A%d",i+2)
		excel.SetSheetRow("Sheet1",axis,&[]interface{}{
			Form.ID,
			Form.ClusterName,
			Form.Database.DatabaseType,
			Form.Database.VIP,
			Form.Database.Port,
			Form.Database.EnvName,
			Form.Database.IdcLocation,
			Form.Database.DnsName,
			Form.Database.DeployPath,
			Form.Database.IpAddress,
			Form.Database.DatabaseSize,
			Form.Database.Project.ProjectFullName,
			Form.Database.SysCompanyInfo.CompanyName,
			Form.DatabaseName,
			Form.Project.ProjectFullName,
			Form.UserName,
			Form.Permission,
			// 要转成字符串 写入excel
		})
	}
	excel.SaveAs(filePath)
	return nil
}
